<?php
/**
 * Created by PhpStorm.
 * User: Admin
 * Date: 2017-12-22
 * Time: 下午 10:30
 */
// error_reporting(E_ALL ^ E_NOTICE);
require_once 'JKSocket.php';

const ROOM_ID = 'room_id';
const ROOMS = 'rooms';

$server = new JKSocket(8800);
$server->config('recv_mode', JKSocket::RECV_MODE_BIN);

$server->onListen(function(JKSocket $server, JKSocketArgument $event) {
    echo "Listen ..\n";
});

$server->onConnect(function (JKSocket $server, JKSocketArgument $event){
    /** @var JKSocket $client */
    $client = $event->getClient();
    $roomId = mt_rand(0, 2);
    $client->set(ROOM_ID, $roomId);
    $date = date('Y-m-d H:i:s');
    $server->setKeyArrayValue(ROOMS, $roomId, $client->getIndex(), $client);
    
    echo "[$date] New clinet #{$client->getIndex()} ({$client->getAddr()}) connected, room $roomId\n";
    $client->send("Enter room $roomId, ID in server:{$client->getIndex()}\r\n");
});

$server->onClose(function (JKSocket $server, JKSocketArgument $event) {
    /** @var JKSocket $client */
    $client = $event->getClient();
    $roomId = $client->get(ROOM_ID);
    $date = date('Y-m-d H:i:s');
    $server->removeKeyArrayValue(ROOMS, $roomId, $client->getIndex());
    echo "[$date] Clinet #{$client->getIndex()} ({$client->getAddr()}) closed, room $roomId\n";
});

$server->onRecv(function (JKSocket $server, JKSocketArgument $event) {
    /** @var JKSocket $client */
    $client = $event->getClient();
    $data = $event->getData();
    file_put_contents('1.log', $data);
    $jsonData = json_decode($data, true);
    
    if(!is_array($jsonData)) {
        $jsonData = [
            'type' => 'message',
            'message' => $data,
        ];
    }
    
    $date = date('Y-m-d H:i:s');
    $roomId = $client->get(ROOM_ID);
    echo "[$date] recv room $roomId #{$client->getIndex()} ({$client->getAddr()}):" . $data . "\n";
    
    if($jsonData['type'] == 'message') {
        $message = $jsonData['message'];
        
        /** @var JKSocket $roomClient */
        foreach ($server->getKeyArrayValue(ROOMS, $client->get(ROOM_ID)) as $roomClient) {
            if($client->getIndex() == $roomClient->getIndex()) {
                continue;
            }

            $roomClient->send("[$date] Client #{$client->getIndex()}({$client->getAddr()}): $message\r\n");
        }
    }
    
});


if($server->listen()->fail()) {
    echo $server->getLastError();
}